﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GTA
{
    public partial class FrmTaskHistory : BaseForm
    {
        #region Local Objects
        private BusinessEntity.Task task;
        private BusinessEntity.TaskHistory historyEdit;
        private List<BusinessEntity.TaskHistory> historyList;
        #endregion

        #region Starting Form
        public FrmTaskHistory(BusinessEntity.Task task)
        {
            InitializeComponent();
            this.task = task;
        }
        private void FrmTaskHistory_Load(object sender, EventArgs e)
        {
            StartForm();
        }
        private void StartForm()
        {
            try
            {
                if (task != null)
                {
                    LoadTaskData();
                    LoadChangeRequestResults();
                    LoadChangeRequestMotivation();
                    LoadGeneralClassifications();
                    LoadCurrentHistory();
                    DefinePermissions();
                }
                else
                {
                    MessageBox.Show("Tarefa não identificada", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                HandleException("Inicialização da tela.", ex);
            }
        }
        #endregion

        #region Events
        private void lstHistory_Resize(object sender, EventArgs e)
        {
            lstHistory.Columns[1].Width = lstHistory.Width - lstHistory.Columns[0].Width - lstHistory.Columns[2].Width - lstHistory.Columns[3].Width - lstHistory.Columns[4].Width - 20;
        }
        private void cmdSaveHistory_Click(object sender, EventArgs e)
        {
            SaveHistory();
        }
        private void cmdCleanForm_Click(object sender, EventArgs e)
        {
            CleanForm();
        }
        private void cmdEditHistory_Click(object sender, EventArgs e)
        {
            EditSelectedHistory();
        }
        private void cmdDeleteHistory_Click(object sender, EventArgs e)
        {
            DeleteSelectedHistory();
        }
        private void cmdPrintHistoryList_Click(object sender, EventArgs e)
        {
            PrintHistoryList();
        }
        private void cmdExportHistoryListXLS_Click(object sender, EventArgs e)
        {
            ExportHistoryListToXLS();
        }
        private void editarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditSelectedHistory();
        }
        private void exclurToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelectedHistory();
        }
        private void imprimirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintHistoryList();
        }
        private void exportarXLSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportHistoryListToXLS();
        }
        private void lstHistory_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstHistory, GetLstHistoryColumnType(e.Column), ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstHistory_DoubleClick(object sender, EventArgs e)
        {
            EditSelectedHistory();
        }
        private void lstHistory_KeyDown(object sender, KeyEventArgs e)
        {
            if (Program.LoggedUser.Name.CompareTo(task.DesignedTo.Name) == 0 &&
                e.KeyCode == Keys.Delete)
                DeleteSelectedHistory();
        }
        #endregion

        #region Methods
        private OrdenacaoListView.Tipo GetLstHistoryColumnType(int column)
        {
            switch (column)
            {
                case 0:
                    return OrdenacaoListView.Tipo.Numerica;
                case 1:
                    return OrdenacaoListView.Tipo.Alfabetica;
                case 2:
                    return OrdenacaoListView.Tipo.Data;
                case 3:
                    return OrdenacaoListView.Tipo.Data;
                case 4:
                    return OrdenacaoListView.Tipo.Alfabetica;
                default:
                    return OrdenacaoListView.Tipo.Alfabetica;
            }
        }
        private void DefinePermissions()
        {
            try
            {
                bool isLoggedUser = Program.LoggedUser.Name.CompareTo(task.DesignedTo.Name) == 0;
                cmdCleanForm.Enabled = isLoggedUser;
                cmdDeleteHistory.Enabled = isLoggedUser;
                cmdSaveHistory.Enabled = isLoggedUser;
                exclurToolStripMenuItem.Enabled = isLoggedUser;
            }
            catch (Exception ex)
            {
                HandleException("Definir a permissão de acesso", ex);
            }
        }
        private void LoadCurrentHistory()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                historyList = bl.ListTaskHistory(Program.LoggedUser.UserProfile != BusinessEntity.UserManagement.Profiler.User ? null : Program.LoggedUser, task);
                lstHistory.Items.Clear();
                if (historyList != null && historyList.Count > 0)
                {
                    foreach (BusinessEntity.TaskHistory itemHistory in historyList)
                    {
                        ListViewItem listItem = new ListViewItem(itemHistory.ID.ToString());
                        listItem.SubItems.Add(itemHistory.Name);
                        listItem.SubItems.Add(itemHistory.StartDate.ToString(DATE_FORMAT_FULL));
                        listItem.SubItems.Add(itemHistory.EndDate.ToString(DATE_FORMAT_FULL));
                        listItem.SubItems.Add(itemHistory.HistoryType.ToString());
                        lstHistory.Items.Add(listItem);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista atual de históricos.", ex);
            }
        }
        private void LoadTaskData()
        {
            try
            {
                txtTaskID.Text = task.ID.ToString();
                txtTitle.Text = task.Title;
            }
            catch (Exception ex)
            {
                HandleException("Carregar os dados da task selecionada.", ex);
            }
        }
        private void LoadChangeRequestResults()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> changeRequestResults = bl.ListChangeRequestResults();
                if (changeRequestResults == null)
                    changeRequestResults = new List<GTA.BusinessEntity.TaskDomain>();
                changeRequestResults.Insert(0, new GTA.BusinessEntity.TaskDomain(0, "Selecione..."));
                cmbChangeRequestResult.DisplayMember = "Description";
                cmbChangeRequestResult.ValueMember = "ID";
                cmbChangeRequestResult.DataSource = changeRequestResults;
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de Change Request Results.", ex);
            }
        }
        private void LoadChangeRequestMotivation()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> changeRequestMotivations = bl.ListChangeRequestMotivations();
                if (changeRequestMotivations != null)
                    changeRequestMotivations.ForEach(item => lstChangeRequestMotivation.Items.Add(new ListViewItem()
                    {
                        Text = item.Description,
                        Tag = item.ID
                    }));
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de Motivos da Change Request.", ex);
            }
        }
        private void LoadGeneralClassifications()
        {
            try
            {
                BusinessLogic.GTA bl = new GTA.BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> list = bl.ListTaskHistoryGeneralClassifications();
                if (list == null)
                    list = new List<GTA.BusinessEntity.TaskDomain>();
                list.Insert(0, new GTA.BusinessEntity.TaskDomain(0, "Selecione..."));
                cmbTaskHistoryGeneralClassification.DisplayMember = "Description";
                cmbTaskHistoryGeneralClassification.ValueMember = "ID";
                cmbTaskHistoryGeneralClassification.DataSource = list;
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de classificações", ex);
            }
        }
        private void SaveHistory()
        {
            try
            {
                if (ValidateForm())
                {
                    BusinessEntity.TaskHistory history = GetHistoryData();
                    BusinessLogic.GTA bl = new BusinessLogic.GTA();
                    bl.SaveTaskHistory(task, Program.LoggedUser, history);
                    MessageBox.Show("Histórico salvo com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    CleanForm();
                    LoadCurrentHistory();
                }
            }
            catch (Exception ex)
            {
                HandleException("Salvar os dados do histórico.", ex);
            }
        }
        private BusinessEntity.TaskHistory GetHistoryData()
        {
            BusinessEntity.TaskHistory history = new GTA.BusinessEntity.TaskHistory();
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    history = new GTA.BusinessEntity.TaskHistoryGeneral()
                    {
                        StartDate = ucHistoryGeneral.txtStartDate.Value,
                        EndDate = ucHistoryGeneral.txtEndDate.Value,
                        HoursDay = Convert.ToInt32(ucHistoryGeneral.txtHoursDay.Text),
                        Description = ucHistoryGeneral.txtDescription.Text.Trim(),
                        HistoryType = GTA.BusinessEntity.TaskHistory.TaskHistoryType.Geral,
                        Name = ucHistoryGeneral.txtName.Text.Trim(),
                        Classification = cmbTaskHistoryGeneralClassification.SelectedIndex > 0 ? cmbTaskHistoryGeneralClassification.SelectedItem as BusinessEntity.TaskDomain : null
                    };
                    break;
                case 1:
                    history = new GTA.BusinessEntity.TaskHistoryChangeRequest()
                    {
                        StartDate = ucHistoryChangeRequest.txtStartDate.Value,
                        EndDate = ucHistoryChangeRequest.txtEndDate.Value,
                        HoursDay = Convert.ToInt32(ucHistoryChangeRequest.txtHoursDay.Text),
                        Description = ucHistoryChangeRequest.txtDescription.Text.Trim(),
                        HistoryType = GTA.BusinessEntity.TaskHistory.TaskHistoryType.ChangeRequest,
                        Name = ucHistoryChangeRequest.txtName.Text.Trim(),
                        ChangeRequestID = Convert.ToInt32(txtChangeRequestID.Text),
                        ChangeRequestResult = cmbChangeRequestResult.SelectedItem as BusinessEntity.TaskDomain,
                        ChangeRequestMotivationList = GetSelectedChangeRequestMotivation()
                    };
                    break;
            }
            if (historyEdit != null)
                history.ID = historyEdit.ID;
            return history;
        }
        private List<BusinessEntity.TaskDomain> GetSelectedChangeRequestMotivation()
        {
            List<BusinessEntity.TaskDomain> list = new List<GTA.BusinessEntity.TaskDomain>();
            foreach (ListViewItem listItem in lstChangeRequestMotivation.CheckedItems)
                list.Add(new GTA.BusinessEntity.TaskDomain()
                {
                    ID = Convert.ToInt32(listItem.Tag),
                    Description = listItem.Text
                });
            return list;
        }
        private bool ValidateForm()
        {
            bool valid = true;
            StringBuilder message = new StringBuilder("Informe os campos obrigatórios:\r\n");
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    valid = ucHistoryGeneral.ValidateForm();
                    if (cmbTaskHistoryGeneralClassification.SelectedIndex == 0)
                    {
                        valid = false;
                        message.Append("\r\nInforme a Classificação.");
                    }
                    message.Append(ucHistoryGeneral.ValidationErrorMessage);
                    break;
                case 1:
                    valid = ucHistoryChangeRequest.ValidateForm();
                    message.Append(ucHistoryChangeRequest.ValidationErrorMessage);
                    if (String.IsNullOrEmpty(txtChangeRequestID.Text))
                    {
                        valid = false;
                        message.Append("\r\nInforme o ID da Change Request");
                    }
                    if (cmbChangeRequestResult.SelectedIndex == 0)
                    {
                        valid = false;
                        message.Append("\r\nInforme o resultado da Change Request");
                    }
                    if (lstChangeRequestMotivation.CheckedItems.Count == 0)
                    {
                        valid = false;
                        message.Append("\r\nSelecione ao menos um motivo da Change Request");
                    }
                    break;
            }

            if (!valid)
                MessageBox.Show(message.ToString(), "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return valid;
        }
        private void CleanForm()
        {
            ucHistoryChangeRequest.CleanForm();
            ucHistoryGeneral.CleanForm();
            txtChangeRequestID.Text = String.Empty;
            tabControl1.SelectedIndex = 0;
            cmbChangeRequestResult.SelectedIndex = cmbChangeRequestResult.Items.Count > 0 ? 0 : -1;
            cmbTaskHistoryGeneralClassification.SelectedIndex = cmbTaskHistoryGeneralClassification.Items.Count > 0 ? 0 : -1;
            foreach (ListViewItem listItem in lstChangeRequestMotivation.CheckedItems)
                listItem.Checked = false;
            historyEdit = null;
        }
        private void EditSelectedHistory()
        {
            try
            {
                CleanForm();
                if (lstHistory.SelectedItems.Count == 1)
                {
                    historyEdit = historyList.Find(it =>
                        it.ID.CompareTo(Convert.ToInt32(lstHistory.SelectedItems[0].SubItems[0].Text)) == 0);
                    switch (historyEdit.HistoryType)
                    {
                        case GTA.BusinessEntity.TaskHistory.TaskHistoryType.Geral:
                            ucHistoryGeneral.LoadData(historyEdit);
                            if (((BusinessEntity.TaskHistoryGeneral)historyEdit).Classification != null &&
                                ((BusinessEntity.TaskHistoryGeneral)historyEdit).Classification.ID != 0 &&
                                ((BusinessEntity.TaskHistoryGeneral)historyEdit).Classification.ID != Int32.MinValue)
                                cmbTaskHistoryGeneralClassification.SelectedValue = ((BusinessEntity.TaskHistoryGeneral)historyEdit).Classification.ID;
                            tabControl1.SelectedIndex = 0;
                            break;
                        case GTA.BusinessEntity.TaskHistory.TaskHistoryType.ChangeRequest:
                            ucHistoryChangeRequest.LoadData(historyEdit);
                            txtChangeRequestID.Text = ((BusinessEntity.TaskHistoryChangeRequest)historyEdit).ChangeRequestID.ToString();
                            cmbChangeRequestResult.SelectedValue = ((BusinessEntity.TaskHistoryChangeRequest)historyEdit).ChangeRequestResult.ID;
                            if (((BusinessEntity.TaskHistoryChangeRequest)historyEdit).ChangeRequestMotivationList != null)
                            {
                                foreach (BusinessEntity.TaskDomain itemMotivation in ((BusinessEntity.TaskHistoryChangeRequest)historyEdit).ChangeRequestMotivationList)
                                {
                                    foreach (ListViewItem listItem in lstChangeRequestMotivation.Items)
                                    {
                                        if (Convert.ToInt32(listItem.Tag).CompareTo(itemMotivation.ID) == 0)
                                        {
                                            listItem.Checked = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            tabControl1.SelectedIndex = 1;
                            break;
                    }
                }
                else
                    MessageBox.Show("Selecione um histórico para editar!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Editar histórico.", ex);
            }
        }
        private void DeleteSelectedHistory()
        {
            try
            {
                if (lstHistory.SelectedItems.Count > 0)
                {
                    if (MessageBox.Show("Deseja realmente excluír os históricos selecionados?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        BusinessLogic.GTA bl = new BusinessLogic.GTA();
                        foreach (ListViewItem listItem in lstHistory.SelectedItems)
                            bl.DeleteTaskHistory(Convert.ToInt32(listItem.SubItems[0].Text));
                        MessageBox.Show("Histórico(s) excluído(s) com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCurrentHistory();
                    }
                }
                else
                    MessageBox.Show("Selecione ao menos um histórico para excluir!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Excluir histórico.", ex);
            }
        }
        private void PrintHistoryList()
        {
            try
            {
                if (historyList != null && historyList.Count > 0)
                {
                    BusinessLogic.GTA bl = new BusinessLogic.GTA();
                    String htmlContent = bl.GetTaskHistoryHTMLFormat(historyList);
                    FrmPrint wd = new FrmPrint(htmlContent);
                    wd.Show(this);
                }
            }
            catch (Exception ex)
            {
                HandleException("Imprimir resultado da pesquisa.", ex);
            }
        }
        private void ExportHistoryListToXLS()
        {
            try
            {
                if (historyList != null && historyList.Count > 0)
                {
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        String pathXlsFile = saveFileDialog.FileName;
                        BusinessLogic.GTA bl = new BusinessLogic.GTA();
                        bl.ExportXlsTaskHistory(historyList, pathXlsFile);
                        if (MessageBox.Show("Arquivo salvo com sucesso.\r\n\r\nDeseja abrir o arquivo!?", "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            System.Diagnostics.Process.Start(pathXlsFile);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Exportar o resultado da pesquisa para XLS.", ex);
            }
        }
        #endregion
    }
}
